<?php
require_once 'phpmailer/class.phpmailer.php';
apf_require_class('Bll_Attendance_EmailLog');
class Tools_SendMail
{

    private static $instance;
    private $hash='';

    public static function get_instance ()
    {
        if (! self::$instance) {
            self::$instance = new Tools_SendMail();
        }
        return self::$instance;
    }
    //如果是重复发送的邮件高这个
    public function set_mail_hash($hash){
        $this->hash = $hash;
    }
    private $cclist = array();
    public function add_cc($cc){
        $this->cclist = $cc;
    }
    public function send ($to, $title, $body, $from = "hr@anjuke.com", $file = null)
    {
        if (empty($to)) {
            // echo "请输入邮件接受者地址";
            return '';
        }
        // 开发环境，邮件发给测试人员
        $to_email = APF::get_instance()->get_config('to_email');
        if ($to_email) {
            $to = $to_email;
        }
        //check email has
        /*apf_require_class('Bll_Attendance_EmailLog');
        $bll = new Bll_Attendance_EmailLog();

        $ck_data = $bll->check_has($hash_str);
        if(!empty($ck_data)){

        }*/
        $bll = new Bll_Attendance_EmailLog();
        $hash_str = md5($to.$title.$body);

        $mail = new PHPMailer(true);
        try {
            $mail->CharSet = "UTF-8";
            $mail->IsSMTP();
            $mail->SMTPDebug = 0;

            $mail->SMTPAuth = true;
            // $mail->SMTPSecure = "ssl";
            $mail->Host = "smtp.anjuke.com";
            $mail->Port = 25;
            $mail->Username = "hr@anjuke.com";
            $mail->Password = "anjuke1qazxsw2";
            $mail->AddReplyTo('shhr@anjuke.com', '人力资源部');
            $mail->AddAddress($to, $to);
            if(!empty($this->cclist)){
                foreach($this->cclist as $val){
                    $mail->AddCC($val[0], $val[1]);
                }
            }
            $mail->SetFrom($from, '人力资源部');
            $mail->Subject = $title;
            $mail->AltBody = ' ';
            $mail->MsgHTML($body);
            if ($file) {
                $mail->AddAttachment($file); // attachment
            }
            $mail->Send();
            if($this->hash){//如外部有设置就说明是重发的
                $this->hash = $hash_str;
                $bll->delete($this->hash);
            }
            // echo "邮件发送成功！";
        } catch (phpmailerException $e) {
            $ck_data = $bll->check_has($hash_str);
            if(empty($ck_data)){
                $in = array(
                        'to_email'=>$to,
                        'title'=>$title,
                        'body'=>$body,
                        'hash_str'=>$hash_str
                );
                $bll->insert($in);
            }
            //echo $e->errorMessage(); // Pretty error messages from PHPMailer
        } catch (Exception $e) {
            $ck_data = $bll->check_has($hash_str);
            if(empty($ck_data)){
                $in = array(
                        'to_email'=>$to,
                        'title'=>$title,
                        'body'=>$body,
                        'hash_str'=>$hash_str
                );
                $bll->insert($in);
            }
            //echo $e->getMessage(); // Boring error messages from anything else!
        }
    }

    /**
     * 出差批准
     * 发给申请人
     *
     * @param unknown_type $userinfo
     * @param unknown_type $leaveinfo
     */
    public function send_on_business_travel_yes ($userinfo, $leaveinfo)
    {
        $title = '出差申请已批准';
        $body = "姓名:" . $userinfo['name'] . "<br>" . "工号:" . $userinfo['code'] .
                 "<br>" . "出差时间：" . $leaveinfo['start_time'] . '-' .
                 $leaveinfo['end_time'] . "<br>" .
                 "以上申请已被{$_SESSION['name']}批准。<br>" . "请登录考勤系统打印该出差单，以便报销之用。";

        $url = Tools_OAUrls::get_instance()->build_print_view_url($leaveinfo['id']);
        $body.="<br/><br/>请点击以下链接打印预览<br><a href ='".$url."'>".$url."</a><br>";

        $this->send($userinfo['email'], $title, $body);
    }

    /**
     * 出差驳回
     * 发给申请人
     *
     * @param unknown_type $userinfo
     * @param unknown_type $leaveinfo
     */
    public function send_on_business_travel_no ($userinfo, $leaveinfo)
    {
        $title = '出差申请已被拒绝';
        $body = "姓名:" . $userinfo['name'] . "<br>" . "工号:" . $userinfo['code'] .
                 "<br>" . "出差时间：" . $leaveinfo['start_time'] . '-' .
                 $leaveinfo['end_time'] . "<br>" .
                 "以上申请已被{$_SESSION['name']}拒绝。<br>" . "请登录考勤系统查看明细。";
        $this->send($userinfo['email'], $title, $body);
    }

    /**
     * 出差批准
     * 发给hr
     *
     * @param unknown_type $userinfo
     * @param unknown_type $leaveinfo
     */
    public function send_on_business_travel_yes_hr ($userinfo, $leaveinfo,$leavedetail,$r_user_info)
    {
        $title = $userinfo['code'] . "    " . $userinfo['name'] . "的出差申请已批准";
        $body =
    '<div style="width: 800px;margin:0 auto;text-align:center;">'.
        '<style type="text/css">'.
            'table{background-color:#000;font-size:14px;}'.
            'table tr{background-color:#FFF; height:25px; line-height:25px;text-align:center;}'.
            'h1{ font-size:20px; padding:5px 6px; margin:0;}'.
            '.b{font-weight:bold;}'.
            '</style>'.
        '<h1>出差申请单</h1>'.
        '<table id="print" cellspacing="1" cellpadding="0" border="1" style="border-collapse:collapse;">'.
          '<tr>'.
            '<td class="b" width="12%">工号</td>'.
            '<td  width="12%">'.$userinfo['code'].'</td>'.
            '<td class="b" width="12%">姓名</td>'.
            '<td width="12%">'.$userinfo['name'].'</td>'.
            '<td class="b" width="12%">部门</td>'.
            '<td width="12%">'.$userinfo['department_name'].'</td>'.
            '<td class="b" width="12%">职务</td>'.
            '<td width="16%">'.$userinfo['job_name'].'</td>'.
          '</tr>'.
          '<tr style="height: 40px;">'.
            '<td class="b">出差事由</td>'.
            '<td colspan=7>'.$leaveinfo['leave_reason'].'</td>'.
          '</tr>'.
          '<tr style="height: 30px;">'.
            '<td class="b">起止日期</td>'.
            '<td colspan=4>'.date("Y年m月d日 H:i", strtotime($leaveinfo['start_time'])).'—'.date("Y年m月d日 H:i", strtotime($leaveinfo['end_time'])).' </td>'.
            '<td class="b">共计天数</td>'.
            '<td colspan=2>'.$leaveinfo['leave_time'].' 天</td>'.
          '</tr>'.
          '<tr>'.
             '<td rowspan=5 class="b">行程</td>'.
              '<td colspan=2 class="b">日期</td>'.
              '<td class="b">出发地</td>'.
              '<td class="b">目的地</td>'.
              '<td colspan=2 class="b">交通工具</td>'.
              '<td class="b">住宿天数</td>'.
          '</tr>';
           foreach($leavedetail as $one){
                $body .=
                '<tr>'.
                  '<td colspan=2>'.date("Y年m月d日 H:i", strtotime($one['trip_date'])).'&nbsp;</td>'.
                  '<td>'.$one['trip_original'].'&nbsp;</td>'.
                  '<td>'.$one['trip_destingation'].'&nbsp;</td>'.
                  '<td colspan=2>'.$one['trip_method'].'&nbsp;'.($one['trip_start_time']==0||$one['trip_start_time']?$one['trip_start_time'].':00':'').'</td>'.
                  '<td>'.$one['trip_hotel'].'&nbsp;</td>'.
                '</tr>';
           }
           $body .=
          '<tr style="height:30px;">'.
            '<td class="b">预支旅费</td>'.
            '<td colspan=7>（大写）　    万　　　仟　　　佰　　　拾　　　元整（￥&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;）</td>'.
           '</tr>'.
          '<tr style="height:40px;">'.
            '<td class="b">备注</td>'.
            '<td colspan=7>'.$leaveinfo['leave_desc'].'</td>'.
          '</tr>'.
          '<tr style="height:40px;">'.
            '<td class="b">申请人、日期</td>'.
            '<td colspan=2>'.$userinfo['name'].'-'.date("Y年m月d日", strtotime($leaveinfo['apply_time'])).'</td>'.
            '<td class="b">部门负责人</td>'.
            '<td colspan=3>'.$r_user_info['name'].'</td>'.
            '<td></td>'.
          '</tr>'.
        '</table>'.
    '</div>';

           $url = Tools_OAUrls::get_instance()->build_print_view_url($leaveinfo['id']);
           $audit_url = Tools_OAUrls::get_instance()->build_audit_list();
           $body.="<br/><br/>请点击以下链接打印预览<br><a href ='".$url."'>".$url."</a><br>".
                   "如需查看更多,请访问<br><a href ='".$audit_url."'>请点击链接审批</a>(".$audit_url.")";
           // 开发环境，邮件发给测试人员
           $to_email = APF::get_instance()->get_config('to_email');
           if ($to_email) {
               $to = $to_email;
           }else{
               $to = "dl-hr@anjuke.com";
           }
           $this->send($to, $title, $body);
    }

    private function __clone ()
    {}

    private function __construct ()
    {}
}
?>
